package dao

import (
	"time"
	"github.com/go-xorm/xorm"
	_ "github.com/go-sql-driver/mysql"
)

const (
	//dataSource = "root:zkm009@tcp(192.168.21.233:3306)/bookstore?charset=utf8"
	dataSource = "root:06UXmbc3dpOHNp4tY1nqFwtatji5wqCX@tcp(rm-bp1wq4598818u4pot.mysql.rds.aliyuncs.com:3306)/bookstore_test?charset=utf8"
)

var (
	engine *xorm.Engine = nil
)

// 初始化数据库
func InitDb() error {
	// 初始化mysql引擎
	mysql, err := xorm.NewEngine("mysql", dataSource)
	if err != nil {
		return err
	}
	//mysql.ShowSQL(true)
	mysql.SetMaxIdleConns(2)                     //设置连接池的空闲数大小
	mysql.SetMaxOpenConns(10)                    //设置最大打开连接数
	mysql.SetConnMaxLifetime(7000 * time.Second) //用于设置连接可被重新使用的最大时间间隔
	mysql.TZLocation, _ = time.LoadLocation("Asia/Shanghai")

	// 检测是否连接成功
	err = mysql.Ping()
	if err != nil {
		mysql.Close()
		return err
	}

	engine = mysql
	return nil
}

func CloseDb() {
	if engine != nil {
		engine.Close()
	}
	engine = nil
}

// 获取会话句柄
func GetSession() *xorm.Session {
	return engine.NewSession()
}

func (a *SysApp) GetAppUrl(path string) string {
	return "http://" + a.BindHost + path + a.AppShort
}
